<template>
    <div class="module-ad-create module-ad-create--buy">
        <loading v-if="isLoading === true" style="margin-top: 32px;"></loading>
        <template v-if="isLoading === false">
            <validator :rules="rules">
                <form class="m-form-page" name="form" action="javascript:;">
                    <div class="col-row">
                        <div class="col-label">
                            <label>交易幣種</label>
                        </div>
                        <div class="col-input">
                            <select class="fn-block col-select"
                                    name="assetcode"
                                    v-model="form.assetcode">
                                <option v-for="item in assetCodeList"
                                :value="item">{{item}}</option>
                            </select>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>國家</label>
                        </div>
                    <div class="col-input">
                            <select class="fn-block col-select"
                                    name="country"
                                    v-model="form.country"  @change='changeCountry'>
                                <option v-for="item in countryList"
                                        :value="item.country">{{item.country}}</option>
                            </select>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>貨幣</label>
                        </div>
                        <div class="col-input">
                            <!-- <select class="fn-block col-select"
                                    name="currency"
                                    v-model="form.currency">
                                <option value="CNY">CNY</option>
                            </select> -->
                        <input :value=form.currency  name="currency" disabled type="text" style="color:#fff">
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>交易價格</label>
                        </div>
                        <div class="col-input col-input--unit">
                              <em class="unit">{{form.currency}}</em>
                            <input type="text"
                                   name="tradePrice"
                                   class="input fn-block"
                                   maxlength="11"
                                   autocomplete="off"
                                   v-number="{model: 'form.tradePrice', precision: 2}"
                                   :placeholder="rules.tradePrice.requiredTip"
                                   v-model="form.tradePrice">
                            <div class="ui-tip"></div>
                        </div>
                        <div class="col-suffix">市場參考價格： <em class="strong">{{marketPrice}}</em> {{form.currency}}</div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>預計購買</label>
                        </div>
                        <div class="col-input col-input--unit">
                              <em class="unit">{{form.currency}}</em>
                            <input type="text"
                                   name="buyPrice"
                                   class="input fn-block"
                                   maxlength="11"
                                   v-number="{model: 'form.buyPrice', precision: 2}"
                                   autocomplete="off"
                                   :placeholder="rules.buyPrice.requiredTip"
                                   v-model="form.buyPrice">
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>備註信息</label>
                        </div>
                        <div class="col-input">
                        <textarea name="remark"
                                  class="input fn-block"
                                  autocomplete="off"
                                  maxlength="120"
                                  placeholder="可在備註信息中填寫您對賣家的要求及您的聯繫方式等信息，有助於您和賣家的溝通及線下交易（選填）"
                                  v-model="form.remark"
                                  rows="5"></textarea>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row col-row--btns">
                        <div class="col-label">
                            <label>&nbsp;</label>
                        </div>
                        <div class="col-text">
                            <button type="submit"
                                    class="ui-btn fn-block"
                                    v-if="isRequesting === false"
                                    @click="submit()">發佈
                            </button>
                            <button type="submit"
                                    class="ui-btn fn-block"
                                    disabled
                                    v-if="isRequesting === true">操作中...
                            </button>
                        </div>
                    </div>
                </form>
            </validator>
        </template>

        <set-nickname v-if="isSettingNickname"
                      v-on:success="onSetNickNameSuccess"
                      v-on:hide="isSettingNickname = false"></set-nickname>

        <ad-success-dialog v-if="showDialog" v-on:hide="hideDialog"></ad-success-dialog>
    </div>
</template>

<script type="text/babel">
import {
  REG_EN_UPP,
  REG_PHONE
} from "../../../../../grsc-base/common/constants";
import Loading from "../../../../../grsc-base/component/Loading.vue";
import Validator from "../../../../../grsc-base/component/Validator/main";
import setNickname from "../../../../component/setNickName.vue";
import adSuccessDialog from "../../ad/component/adSuccessDialog.vue";

import lib from "../../../../common/lib";

import config from "../../config";
import service from "../service";

export default {
  components: {
    Loading,
    Validator,
    setNickname,
    adSuccessDialog
  },
  computed: {
    userLevel() {
      return this.level;
    }
  },
  data() {
    let doType = config.DO_TYPE_CREATE;
    if (this.$route.params.advertId) {
      doType = config.DO_TYPE_UPDATE;
    }

    return {
      isLoading: true,
      doType: doType,
      config: config,
      assetCodeList: [],
      countryList: [],
      isRequesting: false,
      isSettingNickname: false,
      showDialog: false,
      form: {
        assetcode: config.DEFAULT_ASSET_CODE,
        country: "中國",
        currency: "CNY",
        tradePrice: "",
        buyPrice: "",
        remark: ""
      },
      rules: {
        tradePrice: {
          required: true,
          requiredTip: "請輸入交易價格",
          min: 0,
          minTip: "請輸入大於0的價格"
        },
        buyPrice: {
          required: true,
          requiredTip: "請輸入購買金額",
          min: 0,
          minTip: "請輸入大於0的購買金額"
        },
        remark: {
          maxlength: "120",
          maxlengthTip: "最多輸入120個字符"
        }
      },
      marketPrice: "6.6"
    };
  },
  watch: {
    "form.assetcode"(newVal, oldVal) {
      this._fetchCurrentPrice();
    }
  },
  props: {
    level: {
      type: String,
      default: "LEVEL1"
    }
  },
  created() {
    let that = this;

    this._fetchCurrentPrice();

    if (this.doType === config.DO_TYPE_CREATE) {
      $.when(service.getBuyInfo()).done(infoRep => {
        this.isLoading = false;
        dealInfoRep(infoRep);
      });
    } else {
      $.when(
        service.getBuyInfo(),
        service.buyDetailEdit({
          advertId: this.$route.params.advertId
        })
      ).done((infoRep, detailRep) => {
        this.isLoading = false;
        dealInfoRep(infoRep);
        dealDetailRep(detailRep);
      });
    }

    function dealInfoRep(rep) {
      let data;
      if (rep.code === window.CODE.SUCCESS) {
        data = rep.data;
        that.assetCodeList = data.assetcodeList;
        that.countryList = data.countryList;
      }
    }

    function dealDetailRep(rep) {
      if (rep.code === window.CODE.SUCCESS) {
        let data = rep.data;
        that.form.assetcode = data.assetcode;
        that.form.country = data.country;
        that.form.currency = data.currency;
        that.form.tradePrice = data.tradePrice;
        that.form.buyPrice = data.buyPrice;
        that.form.remark = data.remark;
        //                } else if (rep.code === window.CODE.ADVERT_HAS_INVALID.CODE) {
        //                    window.alert({
        //                        content: window.CODE.ADVERT_HAS_INVALID[that.$i18n.locale],
        //                        btnText: '我的廣告'
        //                    }).done(() => {
        //                        window.location.href = './c2c.html#/order/advert';
        //                    });
        //                } else if (rep.code === window.CODE.REQUEST_ERROR.CODE) {
        //                    window.alert({
        //                        content: '該廣告不存在',
        //                        btnText: '我的廣告'
        //                    }).done(() => {
        //                        window.location.href = './c2c.html#/order/advert';
        //                    });
      } else {
        window
          .alert({
            content: rep.msg,
            btnText: "我的廣告"
          })
          .done(() => {
            window.location.href = "./c2c.html#/order/advert";
          });
      }
    }
  },
  methods: {
    _fetchCurrentPrice() {
      lib.getCurrentPriceByCoin(this.form.assetcode, repData => {
        this.marketPrice = repData.priceCNY;
      });
    },

    hideDialog() {
      this.showDialog = false;
    },

    /**
     * 发布
     */
    submit() {
      if (this.rules.$checkAll() === false) {
        return;
      }

      let param = {
        assetcode: this.form.assetcode,
        country: this.form.country,
        currency: this.form.currency,
        tradePrice: this.form.tradePrice,
        buyPrice: this.form.buyPrice,
        remark: this.form.remark
      };
      let header = {};

      this.isRequesting = true;

      if (this.doType === config.DO_TYPE_CREATE) {
        service
          .createAdBuy(param)
          .done(rep => {
            if (rep.code === window.CODE.SUCCESS) {
              this.showDialog = true;
              //                            window.success('操作成功', () => {
              //                                window.location.href = './c2c.html';
              //                            });
            } else if (rep.code === window.CODE.NO_NICKNAME.CODE) {
              this.isSettingNickname = true;
            } else {
              window.error(rep.msg);
            }
          })
          .fail(rep => {
            window.error(rep.msg);
          })
          .always(() => {
            this.isRequesting = false;
          });
      } else {
        param.advertId = this.$route.params.advertId;
        service
          .updateAdBuy(param, header)
          .done(rep => {
            if (rep.code === window.CODE.SUCCESS) {
              window.success("操作成功", () => {
                window.location.href = "./c2c.html";
              });
            } else {
              window.error(rep.msg);
            }
          })
          .fail(rep => {
            window.error(rep.msg);
          })
          .always(() => {
            this.isRequesting = false;
          });
      }
    },
            changeCountry(item){
                    this.form.currency=this.form.country;
                   for(var i=0;i<this.countryList.length;i++) {
                       var item=this.countryList[i];
                       if(item.country===this.form.country){
                           this.form.currency=item.moneyName;
                           this.marketPrice=item.exRate;
                           break;
                       }
                   }
                },
    onSetNickNameSuccess() {
      this.isSettingNickname = false;
      this.submit();
    }
  }
};
</script>

<style lang="sass" rel="stylesheet/scss">
    .module-ad-create--sell {

    }
</style>
